<template>
  <div :class="['device_container',inElectron?'device_container_electron':'']">
    <HeaderNav v-if="!inElectron"></HeaderNav>
    <div v-if="!inElectron" class="btn" @click="handleConnect">{{ $t('device.addNewDevice') }}</div>
    <div class="list" v-show="deviceCardCount > 0">
      <template v-for="(itemArr, index) in filterDeviceList" :key="Math.random().toString(36).substring(2, 15)">
        <template v-for="(item2 ,index2) in itemArr" :key="Math.random().toString(36).substring(2, 15)" >
          <DeviceCard 
            v-if="(deviceAsync(item2)?.protocol == 'default' && index2==0) || (protocolList.includes(deviceAsync(item2)?.protocol) && devcieCanShow(item2))"
            :item2="item2" 
            :protocol="deviceAsync(item2)?.protocol"
            />
        </template>
      </template>
    </div>

    <ElectronWelcome v-if="inElectron && deviceCardCount == 0"></ElectronWelcome>
  </div>
</template>

<script setup>
import HeaderNav from "./HeaderNav.vue";
import DeviceCard from "./DeviceCard.vue";
import ElectronWelcome from "./ElectronWelcome.vue";
import { computed } from "vue";
import { useHidStore } from "../stores/useHidStore.js";
import { useI18n } from 'vue-i18n';
import { inElectron } from '../utils/tools'

const emit = defineEmits(["btnClcik"]); // 声明自定义事件
const hidStore = useHidStore();
const { t } = useI18n();
const props = defineProps({
  deviceList: {
    type: Array,
    default: () => [],
  },
});
console.log("deviceList==：", props.deviceList);

// 协议列表
const protocolList = ['ry_wired','ry-receiver','hfd-receiver','beiyin_uuid','dakai']

const filterDeviceList = computed(() => {
  const groupMap = new Map();

  props.deviceList.forEach((device) => {
    const key = `${device.vendorId}_${device.productId}_${device.productName}`;

    if (!groupMap.has(key)) {
      groupMap.set(key, []);
    }
    groupMap.get(key).push(device);
  });

  // 转换为二维数组
  return Array.from(groupMap.values());
});
console.log("groupMap=:", filterDeviceList.value);

const deviceAsync = computed(() => (currentDevice) => {
  const device = hidStore.hidList?.find(
    (item) =>
      (item.pid == currentDevice.pid && item.vid == currentDevice.vid && item.productName == currentDevice.productName) ||
      (item.pid == currentDevice.pid && item.vid == currentDevice.vid && item.noUseProductName)
  );
  return device;
});

const devcieCanShow = (device)=>{
  const bool = hidStore.hidList?.some(
    (item) =>
      item.pid == device.productId &&
      item.vid == device.vendorId &&
      // item.usagePage == device.usagePage &&
      // item.usage == device.usage
      device.usagePageArr?.includes(item.usagePage) &&
      device.usageArr?.includes(item.usage)
   )
   return bool
} 

// 获取DeviceCard渲染数量的计算属性
const deviceCardCount = computed(() => {
  let count = 0;
  filterDeviceList.value.forEach((itemArr) => {
    itemArr.forEach((item2, index2) => {
      const device = deviceAsync.value(item2);
      if ((device?.protocol == 'default' && index2 == 0) || 
          (protocolList.includes(device?.protocol) && devcieCanShow(item2))) {
        count++;
      }
    });
  });
  return count;
});

const handleConnect = async () => {
  emit("btnClcik");
};

// todo
// const sendYoumeng = ()=>{
//   if (window.aplus_queue) {
//     window.aplus_queue.push({
//       action: "aplus.record",
//       arguments: [
//         "device_login",
//         "CLK",
//         {
//           stat_platform: "Windows",
//           stat_os: "Windows 10",
//           stat_brand: item.displayName,
//           device_identify: `${item.productId}_${item.vendorId}`,
//           connect_type: "usb",
//         },
//       ],
//     });
//   } else {
//     console.warn("友盟SDK未加载，无法发送统计事件");
//   }
// }
</script>

<style scoped>
.device_container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.device_container_electron{
  justify-content: center;
  height: 100vh;
}
.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ff6b35, #ff4500);
  width: 200px;
  height: 44px;
  line-height: 45px;
  border-radius: 22px;
  color: #fff;
  margin-top: 40px;
  margin-bottom: 50px;
  cursor: pointer;
  margin: 0 auto;
  margin-top: 100px;
  font-size: 16px;
  font-weight: bold;
}
.list {
  display: flex;
  flex-wrap: wrap;
  max-width: 950px;
  gap: 50px;
  margin-top: 100px;
  margin-bottom: 100px;
}
</style>
